package middleware

import (
	"context"
	"errors"
	"github.com/go-kratos/kratos/v2/log"
	"github.com/go-kratos/kratos/v2/middleware"
	"runtime/debug"
	"{{cookiecutter.__project_name_snake}}/pkg/errorx"
)

// RecoverMiddleware 创建一个用于处理panic的中间件
func RecoverMiddleware() middleware.Middleware {
	return func(handler middleware.Handler) middleware.Handler {
		return func(ctx context.Context, req interface{}) (reply interface{}, err error) {
			defer func() {
				var msg string
				if rerr := recover(); rerr != nil {
					switch rerr.(type) {
					case errorx.BizError:
						msg = rerr.(errorx.BizError).Error()
					default:
						msg = "系统错误，请稍后再试~"
					}

					// 构建错误日志
					stack := string(debug.Stack())
					log.Error(ctx, "中间件捕获到了异常!", rerr, " stack: ", stack)

					err = errors.New(msg)
				}
			}()
			return handler(ctx, req)
		}
	}
}
